/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-05-24 13:20:54
 */

import { createContext, useContext, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  ADD_BATCH_ITEM,
  ADD_BATCH_LIST,
  ADD_LEVEL_LIST,
  DELETE_BATCH_ITEM,
  SET_ACTIVE_BATCH,
  SET_BATCH_ITEM_PROCESS,
  SET_RECEIVE_WAY,
  SET_SELECT_RECEIVE_TYPE,
  SET_SELECTED_ITEM,
  START_AUDIT,
  UPDATE_BATCH_LIST
} from '../constants';
import { BatchManageReducer } from '../reducers/BatchManageReducer';
import { fetchLevelByATId } from '@/api/archivesType';
import {
  addBatch,
  deleteBatchItem,
  fetchBatchListByPage,
  startBackTask,
  startDetectionTask
} from '@/api/accession';
import { selectItemByKey } from '@/utils/list';
import {
  receiveTypeList,
  receiveWaysList,
  stateList
} from '@/view/accession/BatchManage/dictionaries';
import { startNewApply } from '@/api/workFlow/task';

const initialState = {
  // 当前选中的接收方式
  selectReceiveType: 0,
  // 当前选中的接收类型
  selectReceiveWay: 1,
  // 层级列表
  levelList: [],
  // 批次列表
  batchList: [],
  // 选中的表格条目
  selectItems: [],
  // 选中的批次条目
  activeBatch: {},

  // -------- 字典 --------
  // 接收类型列表
  receiveWaysList,

  // 接收类型列表
  receiveTypeList,

  // 接收方式列表
  receiveModeList: [
    { id: 0, name: '离线接收' },
    { id: 1, name: '在线接收' }
  ],

  // 批次状态列表
  stateList
};

const BatchManageContext = createContext();

const BatchManageContextProvider = (props) => {
  const [state, dispatch] = useReducer(BatchManageReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的接收方式
     */
    setSelectReceiveType(data) {
      dispatch({ type: SET_SELECT_RECEIVE_TYPE, data });
    },

    /**
     * @description: 设置选中的接收类型
     */
    setReceiveWay(data) {
      dispatch({ type: SET_RECEIVE_WAY, data });
    },

    /**
     * @description: 获取档案类型下所有层级
     * @param {number} id
     */
    async fetchATLevel(id) {
      const res = await fetchLevelByATId(id);
      const { data } = res;
      dispatch({ type: ADD_LEVEL_LIST, data, id });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description:
     * @param {*} params
     * @return {*}
     */
    getBatchList(params) {
      return new Promise((resolve, reject) => {
        fetchBatchListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_BATCH_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    updateBatchList(data) {
      dispatch({ type: UPDATE_BATCH_LIST, data });
    },

    /**
     * @description: 更新检测进度方法
     * @param {*} data 进度信息
     */
    setBatchItemProcess(data) {
      const { businessId } = data;
      const item = selectItemByKey(businessId, state.batchList, 'batchNo');
      if (item) {
        dispatch({ type: SET_BATCH_ITEM_PROCESS, data, item });
      }
    },

    addBatchFunc(params) {
      return new Promise((resolve, reject) => {
        addBatch(params)
          .then((res) => {
            message.success('创建成功');
            const { data } = res;
            dispatch({ type: ADD_BATCH_ITEM, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    deleteBatchFunc(id, title = '确认删除此批次？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteBatchItem(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_BATCH_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 设置选中的批次条目
     * @param {any} data 选中的批次条目
     */
    setActiveBatch(data) {
      dispatch({ type: SET_ACTIVE_BATCH, data });
    },

    /**
     * @description: 设置选中的批次条目
     * @param {number} id
     */
    startDetectionTaskFunc(id) {
      startDetectionTask(id).then((res) => {
        message.success('提交成功');
        const { data } = res;
        dispatch({ type: UPDATE_BATCH_LIST, data });
      });
    },

    /**
     * @description: 设置选中的批次条目
     * @param {IStartApplyParams} params 选中的批次条目
     */
    startAuditTaskFunc(params) {
      startNewApply(params).then(() => {
        message.success('提交成功');
        dispatch({ type: START_AUDIT, batchNo: params.applyFormNo });
      });
    },

    /**
     * @description: 设置选中的批次条目
     * @param {number} id 选中的批次条目
     */
    returnBatchFunc(id) {
      startBackTask(id).then((res) => {
        message.success('退回成功');
        const { data } = res;
        dispatch({ type: UPDATE_BATCH_LIST, data });
      });
    }
  };

  const filters = {
    receiveTypeFilter(id) {
      return state.receiveTypeList.find((item) => item.id === id)?.name || '-';
    },
    receiveModeFilter(id) {
      return state.receiveModeList.find((item) => item.id === id)?.name || '-';
    },
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    }
  };

  return (
    <BatchManageContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </BatchManageContext.Provider>
  );
};

export const useBatchManageContext = () => {
  return useContext(BatchManageContext);
};

export { BatchManageContext, BatchManageContextProvider };
